<template>
  <div class="post-form-container">
    <!-- 表单头部 -->
    <div class="form-header">
      <h1 class="h3 mb-0"><i class="bi bi-pencil-square"></i> 发布新帖子</h1>
      <p class="mb-0 mt-1">填写以下信息，让更多人看到您的帖子</p>
    </div>
    
    <!-- 表单主体 -->
    <div class="form-body">
      <!-- 基本信息部分 -->
      <div class="form-section">
        <div class="section-title">
          <i class="bi bi-info-circle"></i> 基本信息
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="category" class="form-label">版块分类 <span class="text-danger">*</span></label>
            <select class="form-select" id="category" v-model="formData.categoryId" required>
              <option value="" disabled selected>请选择帖子所属版块</option>
              <option v-for="category in categories" :key="category.id" :value="category.id">
                {{ category.name }}
              </option> 
            </select>
            <div v-if="formErrors.categoryId" class="text-danger small mt-1">{{ formErrors.categoryId }}</div>
          </div>
          
          <div class="col-md-6 mb-3">
            <label for="title" class="form-label">帖子标题 <span class="text-danger">*</span></label>
            <input type="text" class="form-control" id="title" v-model="formData.title" 
                  placeholder="请输入帖子标题（最多200字）" maxlength="200" required>
            <div class="character-count" :class="getTitleCountClass()">
              {{ formData.title.length }}/200
            </div>
            <div v-if="formErrors.title" class="text-danger small mt-1">{{ formErrors.title }}</div>
          </div>
        </div>

        <div class="row">

        <div class="col-md-6 mb-3">
          <label for="itemType" class="form-label">详细分类</label>
          <select class="form-select" id="itemType" v-model="formData.itemTypeId" :disabled="itemType.length === 0">
            <option value="" selected>请选择详细分类</option>
            <option v-for="item in itemType" :key="item.id" :value="item.id">
              {{ item.name }}
            </option>
          </select>
          <div class="form-text">根据所选版块分类，提供相应的详细分类选项</div>
        </div>

        <div class="col-md-6 mb-3">
          <label for="price" class="form-label">价格</label>
          <div class="input-group price-input-group">
            <span class="input-group-text">¥</span>
            <input type="number" class="form-control" id="price" v-model="formData.price" 
                  placeholder="请输入价格" min="0" step="0.01">
          </div>
          <div v-if="formErrors.price" class="text-danger small mt-1">{{ formErrors.price }}</div>
        </div>
       </div>
              
        <div class="mb-3">
          <label for="content" class="form-label">帖子内容 <span class="text-danger">*</span></label>
          <textarea class="form-control" id="content" v-model="formData.content" 
                    rows="6" placeholder="请输入帖子详细内容" required></textarea>
          <div class="character-count" :class="getContentCountClass()">
            {{ formData.content.length }}/5000
          </div>
          <div v-if="formErrors.content" class="text-danger small mt-1">{{ formErrors.content }}</div>
        </div>


        
        <div class="mb-3">
          <label class="form-label">图片上传（可选）</label>
          <div class="upload-layout">
            <!-- 上传区域 -->
            <div class="upload-section">
              <div 
                class="custom-file-upload" 
                @click="triggerFileInput"
                @dragover.prevent="handleDragOver"
                @dragleave.prevent="handleDragLeave"
                @drop.prevent="handleDrop"
                :class="{ 'drag-over': isDragOver }"
              >
                <div class="upload-icon">
                  <i class="bi bi-cloud-arrow-up-fill"></i>
                </div>
                <h5 class="upload-title">拖拽图片到此处或点击上传</h5>
                <p class="upload-hint">支持 JPG、PNG、WEBP 格式，单张图片不超过 5MB</p>
                <div class="upload-action">
                  <button type="button" class="btn btn-outline-primary btn-sm">
                    <i class="bi bi-folder2-open"></i> 浏览文件
                  </button>
                </div>
              </div>
              <input type="file" ref="fileInput" @change="handleFileUpload" multiple accept="image/*" style="display: none;">
              
              <!-- 已上传图片操作按钮 -->
              <div class="upload-actions" v-if="uploadedImages.length > 0">
                <button type="button" class="btn btn-sm btn-outline-danger" @click="clearAllImages">
                  <i class="bi bi-trash"></i> 清空所有
                </button>
                <button type="button" class="btn btn-sm btn-success" @click="confirmImages">
                  <i class="bi bi-check-circle"></i> 确认接受
                </button>
              </div>
            </div>
            
            <!-- 预览区域 -->
            <div class="preview-section" v-if="uploadedImages.length > 0">
              <div class="image-preview-grid">
                <div class="image-preview-item" v-for="(image, index) in uploadedImages" :key="index">
                  <img :src="image.preview" alt="预览图片">
                  <div class="image-overlay">
                    <button type="button" class="remove-btn" @click="removeImage(index)">
                      <i class="bi bi-x-lg"></i>
                    </button>
                  </div>
                  <div class="image-info">
                    <span class="image-name">{{ image.file.name }}</span>
                    <span class="image-size">{{ formatFileSize(image.file.size) }}</span>
                  </div>
                  <!-- 始终显示的删除按钮 -->
                  <button type="button" class="remove-btn-always-visible btn btn-danger btn-sm" @click="removeImage(index)">
                    <i class="bi bi-trash"></i> 删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 联系与位置信息 -->
      <div class="form-section">
        <div class="section-title">
          <i class="bi bi-geo-alt"></i> 联系与位置信息
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="contact" class="form-label">联系方式</label>
            <input type="text" class="form-control" id="contact" v-model="formData.contactInfo" 
                  placeholder="电话、微信、邮箱等（可选）">
            <div class="form-text">如果您希望公开联系方式，请填写此项</div>
          </div>
          
          <div class="col-md-6 mb-3">
            <label for="location" class="form-label">地点/位置</label>
            <div class="dropdown">
              <input 
                type="text" 
                class="form-control" 
                id="location" 
                v-model="formData.location" 
                @focus="showDropdown = true"
                @blur="hideDropdownWithDelay"
                placeholder="例如：教学楼区域"
              >
              <ul class="dropdown-menu" :class="{ 'show': showDropdown }" aria-labelledby="location">
                <li><button class="dropdown-item" type="button" @mousedown="selectLocation('体育馆主馆')">体育馆主馆</button></li>
                <li><button class="dropdown-item" type="button" @mousedown="selectLocation('校西门停车场')">校西门停车场</button></li>
                <li><button class="dropdown-item" type="button" @mousedown="selectLocation('运动场')">运动场</button></li>
                <li><button class="dropdown-item" type="button" @mousedown="selectLocation('北校区公寓')">北校区公寓</button></li>
                <li><button class="dropdown-item" type="button" @mousedown="selectLocation('教学楼区域')">教学楼区域</button></li>
                <li><button class="dropdown-item" type="button" @mousedown="selectLocation('食堂')">食堂</button></li>
              </ul>
            </div>
            <div class="form-text">可选择预定义位置或输入自定义位置</div>
          </div>
        </div>
      </div>
      <!-- 帖子设置 -->
      <div class="form-section">
        <div class="section-title">
          <i class="bi bi-gear"></i> 帖子设置
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label for="expiry" class="form-label">过期时间</label>
            <input type="datetime-local" class="form-control" id="expiry" v-model="formData.expiredAt">
            <div class="expiry-info">设置后帖子将在指定时间自动下架，留空则永不过期</div>
            <div v-if="formErrors.expiredAt" class="text-danger small mt-1">{{ formErrors.expiredAt }}</div>
          </div>
          
          <div class="col-md-6 mb-3">
            <div class="mb-3">
              <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="urgent" v-model="formData.isUrgent">
                <label class="form-check-label" for="urgent">
                  标记为紧急信息
                  <span class="urgent-badge ms-2">紧急</span>
                </label>
              </div>
              <div class="form-text">紧急信息将在列表中突出显示</div>
            </div>
            
            <div class="mb-3">
              <div class="form-check">
                <input class="form-check-input" type="checkbox" id="agree" v-model="agreeTerms">
                <label class="form-check-label" for="agree">
                  我已阅读并同意 <a href="#" @click.prevent="showTerms = true">《用户发布协议》</a>
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 预览部分 -->
      <div class="form-section" v-if="formData.title || formData.content">
        <div class="section-title">
          <i class="bi bi-eye"></i> 帖子预览
        </div>
        
        <div class="preview-card">
          <div class="preview-title">{{ formData.title || '（无标题）' }}</div>
          <div class="preview-content">{{ formData.content || '（无内容）' }}</div>
          <div class="preview-meta">
            <span v-if="formData.price" class="me-3"><strong>价格:</strong> ¥{{ formData.price }}</span>
            <span v-if="formData.location" class="me-3"><strong>地点:</strong> {{ formData.location }}</span>
            <span v-if="formData.isUrgent" class="urgent-badge me-2">紧急</span>
            <span class="status-badge status-pending">待审核</span>
          </div>
        </div>
      </div>
      
      <!-- 发布说明 -->
      <div class="form-note">
        <i class="bi bi-info-circle me-1"></i> 
        提示：帖子提交后需要经过管理员审核，审核通过后才会在平台上显示。如有问题请联系客服。
      </div>
    </div>
    
    <!-- 表单底部 -->
    <div class="form-footer">
      <div>

      </div>
      <div>
        <button type="button" class="btn btn-secondary me-2" @click="resetForm">
          <i class="bi bi-arrow-clockwise"></i> 重置
        </button>
        <button type="button" class="btn btn-primary" @click="submitForm">
          <i class="bi bi-send"></i> 提交帖子
        </button>
      </div>
    </div>
    
    <!-- 用户协议模态框 -->
    <div ref="termsModal" class="modal fade" id="termsModal" tabindex="-1" aria-labelledby="termsModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="termsModalLabel">用户发布协议</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <h6>一、总则</h6>
            <p>用户在使用本平台发布信息前，应当仔细阅读本协议，并同意遵守本协议及所有平台规则。</p>
            
            <h6>二、信息发布规范</h6>
            <p>1. 用户发布的信息必须真实、准确、合法，不得包含虚假、欺诈、侵权等内容。</p>
            <p>2. 禁止发布任何违法、违规、违背社会公德的信息。</p>
            <p>3. 用户需对发布的信息承担全部法律责任。</p>
            
            <h6>三、审核机制</h6>
            <p>所有用户发布的信息需经过平台审核，审核通过后方可公开显示。</p>
            
            <h6>四、免责声明</h6>
            <p>平台仅提供信息发布服务，不对用户发布的信息内容承担法律责任。</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-bs-dismiss="modal">我已阅读并同意</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import { Modal } from 'bootstrap'; // 引入Bootstrap的Modal组件

import { getCategoriesListService,
         createPostService,
         getPostTypesService
        } from '@/api/post.js'

// 表单数据
const formData = ref({
  categoryId: '',
  itemTypeId: '', // 添加详细分类字段
  title: '',
  content: '',
  contactInfo: '',
  price: null,
  location: '',
  isUrgent: false,
  expiredAt: ''
});

// 下拉菜单显示状态
const showDropdown = ref(false);

// 表单验证错误信息
const formErrors = ref({
  categoryId: '',
  title: '',
  content: '',
  price: '',
  expiredAt: ''
});

// 表单验证规则
const rules = ref({
  categoryId: [
    { 
      required: true, 
      validator: (rule, value, callback) => {
        const categoryId = parseInt(value);
        if (!value) {
          callback(new Error('请选择版块分类'));
        } else if (isNaN(categoryId) || categoryId <= 0) {
          callback(new Error('请选择有效的版块分类'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value.length > 200) {
          callback(new Error('帖子标题长度不能超过200字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value.length > 5000) {
          callback(new Error('帖子内容长度不能超过5000字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  price: [
    {
      validator: (rule, value, callback) => {
        if (value && (isNaN(value) || value < 0)) {
          callback(new Error('价格必须是非负数'));
        } else if (value && value > 1000) {
          callback(new Error('价格不能超过1000'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  expiredAt: [
    {
      validator: (rule, value, callback) => {
        if (value && new Date(value) < new Date()) {
          callback(new Error('过期时间不能早于当前时间'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 其他响应式数据
const uploadedImages = ref([]);// 上传的图片列表
const agreeTerms = ref(false);// 用户是否同意协议
const showTerms = ref(false);// 是否显示用户协议
const fileInput = ref(null);// 文件上传输入框引用
const isDragOver = ref(false); // 拖拽状态
const modalInstance = ref(null); // 模态框实例
const termsModal = ref(null); // 用户协议模态框引用

const categories = ref([]);// 版块数据
const itemType = ref([]);//详细分类

// 隐藏下拉菜单
const hideDropdown = () => {
  showDropdown.value = false;
};

// 延迟隐藏下拉菜单
const hideDropdownWithDelay = () => {
  setTimeout(() => {
    hideDropdown();
  }, 200);
};

// 选择预定义位置
const selectLocation = (location) => {
  formData.value.location = location;
  hideDropdown();
};

// 验证单个字段
const validateField = (fieldName) => {
  const fieldRules = rules.value[fieldName];
  const value = formData.value[fieldName];
  
  if (!fieldRules) {
    formErrors.value[fieldName] = '';
    return true;
  }
  
  for (const rule of fieldRules) {
    // 检查必填项
    if (rule.required && (!value || value.toString().trim() === '')) {
      formErrors.value[fieldName] = rule.message || '此字段为必填项';
      return false;
    }
    
    // 执行自定义验证器
    if (rule.validator) {
      let isValid = true;
      let errorMessage = '';
      
      rule.validator(rule, value, (error) => {
        if (error) {
          isValid = false;
          errorMessage = error.message || error;
        }
      });
      
      if (!isValid) {
        formErrors.value[fieldName] = errorMessage;
        return false;
      }
    }
  }
  
  // 如果验证通过，清除错误信息
  formErrors.value[fieldName] = '';
  return true;
};

// 验证整个表单
const validateForm = () => {
  let isValid = true;
  
  // 验证所有字段
  Object.keys(rules.value).forEach(fieldName => {
    if (!validateField(fieldName)) {
      isValid = false;
    }
  });
  
  return isValid;
};

// 监听表单字段变化并进行验证
const watchFields = ['categoryId', 'title', 'content', 'price', 'expiredAt'];
watchFields.forEach(field => {
  watch(() => formData.value[field], () => {
    validateField(field);
  });
});

// 计算属性：表单是否有效

// 标题文字类容大小
const getTitleCountClass = () => {
  const length = formData.value.title.length;
  if (length > 180) return 'warning';
  if (length >= 200) return 'danger';
  return '';
};

//帖子类容大小
const getContentCountClass = () => {
  const length = formData.value.content.length;
  if (length > 4500) return 'warning';
  if (length >= 5000) return 'danger';
  return '';
};

// 触发文件上传
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理拖拽悬停事件
const handleDragOver = (event) => {
  event.preventDefault();
  isDragOver.value = true;
};

// 处理拖拽离开事件
const handleDragLeave = () => {
  isDragOver.value = false;
};

// 处理文件拖拽放下事件
const handleDrop = (event) => {
  event.preventDefault();
  isDragOver.value = false;
  
  const files = event.dataTransfer.files;
  if (files && files.length > 0) {
    processFiles(files);
  }
};

// 处理文件上传
const handleFileUpload = (event) => {
  const files = event.target.files;
  if (!files.length) return;
  
  processFiles(files);
};

// 处理文件的通用方法
const processFiles = (files) => {
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    // 检查文件类型是否为图片
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件 (JPG, PNG, WEBP)');
      continue;
    }
    
    // 检查是否为支持的图片格式
    const supportedTypes = ['image/jpeg', 'image/png', 'image/webp'];
    if (!supportedTypes.includes(file.type.toLowerCase())) {
      // 对于某些浏览器，可能需要检查文件扩展名
      const fileName = file.name.toLowerCase();
      const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
      const supportedExtensions = ['jpg', 'jpeg', 'png', 'webp'];
      
      if (!supportedExtensions.includes(fileExtension)) {
        alert('请选择支持的图片格式 (JPG, PNG, WEBP)');
        continue;
      }
    }
    
    if (file.size > 5 * 1024 * 1024) {
      alert('文件大小不能超过5MB');
      continue;
    }
    
    const reader = new FileReader();
    reader.onload = (e) => {
      uploadedImages.value.push({
        file: file,
        preview: e.target.result
      });
    };
    reader.readAsDataURL(file);
  }
};

// 移除图片
const removeImage = (index) => {
  uploadedImages.value.splice(index, 1);
};

// 清空所有图片
const clearAllImages = () => {
  if (confirm('确定要清空所有已上传的图片吗？')) {
    uploadedImages.value = [];
  }
};

// 确认接受图片
const confirmImages = () => {
  alert(`已确认接受 ${uploadedImages.value.length} 张图片`);
  // 这里可以添加其他确认后的逻辑
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes < 1024) {
    return bytes + ' B';
  } else if (bytes < 1024 * 1024) {
    return (bytes / 1024).toFixed(1) + ' KB';
  } else {
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
  }
};

// 重置表单
const resetForm = () => {
  if (confirm('确定要重置表单吗？所有输入的内容将丢失。')) {
    formData.value = {
      categoryId: '',
      itemTypeId: '',
      title: '',
      content: '',
      contactInfo: '',
      price: null,
      location: '',
      isUrgent: false,
      expiredAt: ''
    };
    uploadedImages.value = [];
    agreeTerms.value = false;
    
    // 清空所有验证错误
    Object.keys(formErrors.value).forEach(key => {
      formErrors.value[key] = '';
    });
  }
};

// 提交表单前处理数据
const processDataForSubmit = () => {
  // 深拷贝表单数据
  const submitData = { ...formData.value };
  
  // 处理详细分类默认值
  // 如果版块是二手市场(id=1)或失物招领(id=2)且未选择详细分类，则设置为"其他"(id=1)
  if ((submitData.categoryId == 1 || submitData.categoryId == 2) && !submitData.itemTypeId) {
    // 查找"其他"分类的id
    const otherItem = itemType.value.find(item => item.name === '其他');
    if (otherItem) {
      submitData.itemTypeId = otherItem.id;
    } 
  }
  
  // 处理过期时间格式，将 ISO 格式转换为后端期望的格式
  if (submitData.expiredAt) {
    // 将 "yyyy-MM-ddTHH:mm" 或 "yyyy-MM-ddTHH:mm:ss" 转换为 "yyyy-MM-dd HH:mm:ss"
    const date = new Date(submitData.expiredAt);
    // 使用 toLocaleString 方法格式化日期时间
    submitData.expiredAt = date.toLocaleString('sv-SE'); // 'sv-SE' 返回 'yyyy-MM-dd HH:mm:ss' 格式
  }
  
  return submitData;
};

const submitForm = async () => {
  console.log('提交的数据:', formData.value);
  
  // 提交前验证整个表单
  if (!validateForm()) {
    alert('表单填写有误，请检查后重新提交');
    return;
  }
  
  // 检查是否同意用户协议（如果不是必须的，可以只给出提示）
  if (!agreeTerms.value) {
    const confirmResult = confirm('您尚未同意用户发布协议，是否继续提交？');
    if (!confirmResult) {
      return;
    }
  }
  
  // 处理数据并提交
  const submitData = processDataForSubmit();
  // 传递整个uploadedImages数组，后端支持多图片上传
  await createPostService(submitData, uploadedImages.value);
  alert('帖子提交成功！等待管理员审核。');
  resetForm();
};

// 监听showTerms变化来控制模态框显示
watch(showTerms, (newVal) => {
  if (!modalInstance.value && termsModal.value) {
    modalInstance.value = new Modal(termsModal.value);
    
    // 监听模态框隐藏事件，确保焦点正确处理
    termsModal.value.addEventListener('hidden.bs.modal', () => {
      showTerms.value = false;
    });
  }
  
  if (newVal) {
    modalInstance.value?.show();
  }
});

// 清理模态框实例
onUnmounted(() => {
  if (modalInstance.value) {
    // 移除事件监听器
    if (termsModal.value) {
      termsModal.value.removeEventListener('hidden.bs.modal', () => {
        showTerms.value = false;
      });
    }
    modalInstance.value.dispose();
    modalInstance.value = null;
  }
});

//详细分类
const fetchItemType = async () => { 
  //只有formData.value.categoryId为1和2才执行
  if(formData.value.categoryId !== 1 && formData.value.categoryId !== 2) {
    itemType.value = [];
    // 清空详细分类选择
    formData.value.itemTypeId = '';
    return;
  }
  
  try {
    const response = await getPostTypesService(formData.value.categoryId);
    itemType.value = response.data || response; // 确保正确处理返回的数据
    console.log('详细分类数据:', itemType.value);
  } catch (error) {
    console.error('获取详细分类失败:', error);
    itemType.value = [];
    formData.value.itemTypeId = '';
  }
};  

// 监听版块分类变化
watch(() => formData.value.categoryId, () => {
  fetchItemType();
});

// 初始化
onMounted(() => {
  // 获取版块数据
  getCategoriesListService().then((res) => {
    categories.value = res.data;
    console.log('获取到的分类列表:', res.data); // 调试信息
  });
  // 初始化时也加载详细分类
  fetchItemType();
});
</script>

<style>
:root {
  --primary-color: #3498db;
  --secondary-color: #2c3e50;
  --success-color: #2ecc71;
  --warning-color: #f39c12;
  --danger-color: #e74c3c;
  --light-bg: #f8f9fa;
  --upload-border: #d1d1d1;
  --upload-hover: #3498db;
  --upload-bg: #f8f9fa;
}

body {
  background-color: #f5f7fa;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.post-form-container {
  max-width: 900px;
  margin: 2rem auto;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  overflow: hidden;
}

.form-header {
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  color: white;
  padding: 1.5rem;
  border-bottom: 1px solid #dee2e6;
}

.form-body {
  padding: 2rem;
  background-color: white;
}

.form-section {
  margin-bottom: 2rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #eaeaea;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--secondary-color);
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
}

.section-title i {
  margin-right: 0.5rem;
  color: var(--primary-color);
}

.price-input-group {
  max-width: 300px;
}

.character-count {
  font-size: 0.875rem;
  color: #6c757d;
  text-align: right;
  margin-top: 0.25rem;
}

.character-count.warning {
  color: var(--warning-color);
}

.character-count.danger {
  color: var(--danger-color);
}

.preview-card {
  border: 1px dashed #ccc;
  border-radius: 8px;
  padding: 1rem;
  margin-top: 1rem;
  background-color: var(--light-bg);
}

.preview-title {
  font-weight: 600;
  font-size: 1.1rem;
  margin-bottom: 0.5rem;
}

.preview-content {
  color: #555;
  line-height: 1.5;
}

.preview-meta {
  font-size: 0.875rem;
  color: #777;
  margin-top: 0.5rem;
}

.form-footer {
  background-color: var(--light-bg);
  padding: 1.5rem;
  border-top: 1px solid #dee2e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.urgent-badge {
  background-color: var(--warning-color);
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 600;
}

.status-badge {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 600;
}

.status-pending {
  background-color: #f8f9fa;
  color: #6c757d;
  border: 1px solid #6c757d;
}

.custom-file-upload {
  border: 2px dashed var(--upload-border);
  border-radius: 12px;
  padding: 2.5rem 1.5rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: var(--upload-bg);
  position: relative;
  overflow: hidden;
}

.custom-file-upload:hover {
  border-color: var(--upload-hover);
  background-color: #e3f2fd;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-file-upload.drag-over {
  border-color: var(--upload-hover);
  background-color: #e3f2fd;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(52, 152, 219, 0.3);
}

.custom-file-upload .upload-icon {
  font-size: 3rem;
  color: var(--upload-hover);
  margin-bottom: 1rem;
}

.custom-file-upload .upload-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
}

.custom-file-upload .upload-hint {
  color: #666;
  margin-bottom: 1.5rem;
}

.custom-file-upload .upload-action .btn {
  transition: all 0.2s;
}

.custom-file-upload .upload-action .btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.upload-layout {
  display: flex;
  gap: 1.5rem;
  flex-wrap: wrap;
}

.upload-section {
  flex: 1;
  min-width: 300px;
}

.preview-section {
  flex: 1;
  min-width: 300px;
}

@media (max-width: 768px) {
  .upload-layout {
    flex-direction: column;
  }
  
  .upload-section,
  .preview-section {
    min-width: 100%;
  }
}

.upload-actions {
  display: flex;
  gap: 0.5rem;
  margin-top: 1rem;
  justify-content: flex-end;
}

.upload-actions .btn {
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.image-preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 15px;
  max-height: 400px;
  overflow-y: auto;
  padding: 0.5rem;
}

.image-preview-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  transition: all 0.3s ease;
  min-height: 160px; /* 增加最小高度以容纳删除按钮 */
}

.image-preview-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.image-preview-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  display: block;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview-item:hover .image-overlay {
  opacity: 1;
}

.image-overlay .remove-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  backdrop-filter: blur(2px);
}

.image-overlay .remove-btn:hover {
  background: rgba(231, 76, 60, 0.9);
  transform: scale(1.1);
}

/* 始终可见的删除按钮 */
.remove-btn-always-visible {
  position: absolute;
  top: 5px;
  right: 5px;
  border: none;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 0.7rem;
  display: flex;
  align-items: center;
  gap: 2px;
  opacity: 0;
  transform: translateY(-10px);
  transition: all 0.3s ease;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.image-preview-item:hover .remove-btn-always-visible {
  opacity: 1;
  transform: translateY(0);
}

.remove-btn-always-visible:hover {
  transform: scale(1.05);
}

.image-info {
  padding: 0.5rem;
}

.image-name {
  font-size: 0.75rem;
  font-weight: 500;
  color: #333;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-size {
  font-size: 0.7rem;
  color: #666;
  display: block;
  margin-top: 0.2rem;
}

@media (max-width: 768px) {
  .custom-file-upload {
    padding: 1.5rem;
  }
  
  .custom-file-upload .upload-icon {
    font-size: 2rem;
  }
  
  .custom-file-upload .upload-title {
    font-size: 1rem;
  }
  
  .image-preview-grid {
    grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
    gap: 10px;
  }
  
  .image-preview-item img {
    height: 100px;
  }
}
</style>